
const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

const mongoose = require('mongoose')
const bodyParser = require('koa-bodyparser')
const json = require('koa-json')
const dbConfig = require('./dbs/config')
const admin = require('./dbs/Interface/admin')
const article = require('./dbs/Interface/article')
const tag = require('./dbs/Interface/tag')
const message = require('./dbs/Interface/message')

const checkToken = require('./utils/check-token')

const app = new Koa()
const host = process.env.HOST || 'localhost'
const port = process.env.PORT || 8083

app.use(bodyParser({
  extendTypes: ['json', 'form', 'text']
}))

app.use(json())

app.use(checkToken())

// 连接数据库
mongoose.connect(dbConfig.dbs, {
  useNewUrlParser: true
}, err => {
  if (err) return console.log(err)
  console.log('数据库连接成功')
})

async function start() {
  // Import and Set Nuxt.js options
  let config = require('../nuxt.config.js')
  config.dev = !(app.env === 'production')
  
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }
  
  // 路由
  app.use(admin.routes()).use(admin.allowedMethods())
  app.use(article.routes()).use(article.allowedMethods())
  app.use(tag.routes()).use(tag.allowedMethods())
  app.use(message.routes()).use(message.allowedMethods())

  app.use(ctx => {
    ctx.status = 200 // koa defaults to 404 when it sees that status is unset

    return new Promise((resolve, reject) => {
      ctx.res.on('close', resolve)
      ctx.res.on('finish', resolve)
      nuxt.render(ctx.req, ctx.res, promise => {
        // nuxt.render passes a rejected promise into callback on error.
        promise.then(resolve).catch(reject)
      })
    })
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
